/*
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { HvigorNode, HvigorPlugin } from '@ohos/hvigor'
import { PluginConfig } from './models'
import { FileManager } from './utils/FileManager'
import { RouterPlugin } from './RouterPlugin'
import { CONSTANTS } from './utils/Constants'
import { logger, LogLevel } from './utils/Logger'

// 默认日志配置
const DEFAULT_LOGGING_CONFIG = {
  level: LogLevel.INFO,
  useColors: true,
  showTimestamp: true,
  showSource: true
}

/**
 * 配置日志工具
 * @param pluginConfig 插件配置
 */
function configureLogger(pluginConfig: PluginConfig): void {
  // 合并默认配置和用户配置
  const loggingConfig = {
    ...DEFAULT_LOGGING_CONFIG,
    ...pluginConfig.logging
  };
  
  // 配置日志实例
  logger.configure(loggingConfig);
}

// hvigor中配置的插件方法
export function etsGeneratorPlugin(pluginConfig: PluginConfig): HvigorPlugin {
  // 配置日志
  configureLogger(pluginConfig);
  
  return {
    pluginId: CONSTANTS.PLUGIN_ID,
    apply(node: HvigorNode) {
      // 获取模块名
      pluginConfig.moduleName = node.getNodeName();
      // 获取模块路径
      pluginConfig.modulePath = node.getNodePath();
      
      const routerPlugin = new RouterPlugin(pluginConfig);
      routerPlugin.execute();
    }
  }
}

// 外部调用清理方法的接口
export function cleanGeneratedFiles(pluginConfig: PluginConfig) {
  // 配置日志
  configureLogger(pluginConfig);
  
  const fileManager = new FileManager(pluginConfig);
  fileManager.clean();
}

// 导出日志相关类型，方便用户配置
export { LogLevel };


